import { LoginReq, refreshUserInfo, reLoginReq, userLogin } from '@/api/user'
import { defineStore } from 'pinia'
import { IUserState } from './types'
import pinia from '..'

export const useUserStoreHooks = defineStore('userInfo', {
	state(): IUserState {
		return {
			username: '如颖随鑫',
			accessToken: '',
			roles: ['common']
		}
	},
	getters: {},
	actions: {
		async storeUserLogin(data: LoginReq) {
			try {
				const resp = await userLogin(data)
				this.username = resp.username
				this.accessToken = resp.accessToken
				this.roles = resp.roles
				return resp
			} catch (error) {}
		},
		async storeRefreshToken(data: reLoginReq) {
			try {
				const resp = await refreshUserInfo(data)
				this.username = resp.username
				this.accessToken = resp.accessToken
				this.roles = resp.roles
			} catch (error) {
				this.accessToken = ''
			}
		},
		logout() {
			localStorage.removeItem('userInfo')
		}
	},
	persist: {
		key: 'userInfo',
		storage: localStorage,
		pick: ['username', 'accessToken']
	}
})

export const useUserStore = () => {
	return useUserStoreHooks(pinia)
}
